'use strict'

	$(function(){
		consultationVideoPageControl.pageInit();
	});

	var consultationVideoPageControl = {
			ifLog : true,
			sendPCCandidateFlag : true,
			receivePCCandidateFlag : true,
			sendCandidateCount : 0,
			receiveCandidateCount : 0,
			sendCandidateArray : new Array(),
			receiveCandidateArray : new Array(),
			layerStatus : {},
			localStream : null,
			remoteStream : null,
			localvideoEle : null,
			remotevideoEle : null,
			sendPC : null,
			receivePC : null,
			turnCfg : null,
			
			pageInit : function(){
				consultationVideoPageControl.layerStatus.loadIndex = layer.msg("正在加载....",
						{
							/*closeBtn:1,*/
							shade: [0.8, '#393D49'],
							time:0,
							btn: ['取消'],
							btn1 : function(){
								backFun();
							}
						});
				$.ajax({
					  url: contextPath+"/frontend/cfginfo/turncfg",
					  type: "GET",
					  success: function(succ){
						  consultationVideoPageControl.turnCfg = JSON.parse(succ);
						  consultationVideoPageControl.createSendPC();
						  
						  navigator.mediaDevices.getUserMedia({audio: true,video: true}).then(
								function(stream){
									consultationVideoPageControl.getLocalStreamSucc(stream);
								}
							).catch(
								function(err){
									consultationVideoPageControl.getLocalStreamFail(err);
								}
							);
					  },
					  error: function(err){
						  layer.msg("加载失败....",
						  {
								/*closeBtn:1,*/
								shade: [0.8, '#393D49'],
								time:0,
								btn: ['重试','返回'],
								btn1 : function(){
									window.location.reload();
								},
								btn2 : function(){
									backFun();
								}
						  });
					  }
				});
			},
			getLocalStreamSucc : function(stream){
				consultationVideoPageControl.localStream = stream;
				consultationVideoPageControl.localvideoEle = document.getElementById("localVideo");
				consultationVideoPageControl.remotevideoEle = document.getElementById("remoteVideo");
				consultationVideoPageControl.localvideoEle.srcObject = stream;
				consultationVideoPageControl.remotevideoEle.srcObject = stream;
				
				//initWebSocket();
				window.socketObj = new socketWebrtc();
				window.socketObj.start();
			},
			getLocalStreamFail : function(err){
				/*var errMsg = "出错了 : ";
				for(var x in err){
					if(x != "constraint"){
						errMsg = errMsg + err[x] + "    ::    ";
					}else{
						errMsg = errMsg + JSON.stringify(err[x]);
					}
				}
				layer.msg(errMsg,{time:0,closeBtn:2});*/
				consultationVideoPageControl.layerStatus.loadIndex = layer.msg("媒体设备获取失败!请检查您的摄像头和音频拾取设备后再尝试视频会诊...",{/*closeBtn:1,*/shade: [0.8, '#393D49'],time:0,btn: ['退出'],btn1 : function(){backFun();}});
			},
			handleContorlCommand : function(comm,callBack){
				if(consultationVideoPageControl.ifLog){
					console.log("command:"+comm.command);
				}
				switch(comm.command){
					case "init":
						consultationVideoPageControl.joinRoom();
						break;
					case "start":
						var expertInfoViewEle = document.getElementById("expertInfoView");
						expertInfoViewEle.innerText = "正在会诊";
						
						consultationVideoPageControl.sendPCCreateOffer();
						break;
					case "checkUser":
						if(callBack){
							callBack('ok');
						}
						break;
					case "otherSiteOnVideo":
						consultationVideoPageControl.layerStatus.loadIndex = layer.msg("此帐号在别处正在会诊....",{/*closeBtn:1,*/shade: [0.8, '#393D49'],time:0,btn: ['退出'],btn1 : function(){backFun();}});
						break;
					case "remoteLeftRoom":
						consultationVideoPageControl.layerStatus.loadIndex = layer.msg("对方离开!",{/*closeBtn:1,*/shade: [0.8, '#393D49'],time:0,btn: ['退出'],btn1 : function(){backFun();}});
						break;
					default:
					   	break;
				}
			},
			handleRTCSdp : function(user,sdp){
				if(consultationVideoPageControl.ifLog){
					console.log("==receiveMsg==:"+sdp.type+"===>fromPC:"+sdp.fromPC);
				}
				if(user == socketUserName){
					return;
				}
				switch(sdp["type"]){
					case "offer":
						consultationVideoPageControl.sendPCSetRemoteDesc(sdp);
						break;
					case "answer":
						consultationVideoPageControl.sendPC.setRemoteDescription(new RTCSessionDescription(sdp)).then(function(){
							if (consultationVideoPageControl.ifLog) {
								 console.log("set remote answer succ");
							}
						}).catch(function(e){
							console.log("set remote answer error  :"+e);
						});
						break;
					case "candidate":
						consultationVideoPageControl.addIceCandidate(sdp);
						break;
					default:
					   	break;
				}
			},
			joinRoom : function(){
				window.socketObj.socketIO.emit('joinRoom',socketUserName,socketRoomName,function(backData){
					if (consultationVideoPageControl.ifLog) {
						 console.log("joinRoom backData:"+backData.state);
					}
					switch(backData.state){
					case 'error':/*信息错误*/
						consultationVideoPageControl.layerStatus.loadIndex = layer.msg("系统错误....",{/*closeBtn:1,*/shade: [0.8, '#393D49'],time:0,btn: ['退出'],btn1 : function(){backFun();}});
						break;
					case 'ok':/*加入成功*/
						layer.closeAll();
						break;
					case 'alreadyInRoom':/*申请者冲突*/
						consultationVideoPageControl.layerStatus.loadIndex = layer.msg("已在会诊房间或此帐号在别处正在会诊....",{/*closeBtn:1,*/shade: [0.8, '#393D49'],time:0,btn: ['退出'],btn1 : function(){backFun();}});
						break;
					case 'roomFull':/*专家冲突*/
						consultationVideoPageControl.layerStatus.loadIndex = layer.msg("其他 专家正在进行本次会诊,您可稍后再试...",{/*closeBtn:1,*/shade: [0.8, '#393D49'],time:0,btn: ['退出'],btn1 : function(){backFun();}});
						break;
					default:
					   	break;
					}
				});
			},
			createSendPC : function(){
				consultationVideoPageControl.sendPC = new RTCPeerConnection(/*null*/consultationVideoPageControl.turnCfg);
				
				try {
					consultationVideoPageControl.sendPC.createDataChannel('sendPCDataChannel', {ordered: false});
				} catch (e) {
					console.log(e);
				}
				
				consultationVideoPageControl.sendPC.onaddstream = function(evt){
					consultationVideoPageControl.sendPCAddStreamEvent(evt);
				};
												 
				consultationVideoPageControl.sendPC.onicecandidate = function(evt){
					consultationVideoPageControl.sendPCIcecandidateEvent(evt);
				};
			},
			sendPCCreateOffer : function(){
				let options = {
				    'offerToReceiveAudio': 1,
				    'offerToReceiveVideo': 1    
				};
				consultationVideoPageControl.sendPC.addStream(consultationVideoPageControl.localStream);
				consultationVideoPageControl.sendPC.createOffer(/*options*/).then(function(offer){
					consultationVideoPageControl.createOfferSucc(offer);
				}).catch(function(err) {
					console.log(err);
				});
			},
			createOfferSucc : function(offer){
				consultationVideoPageControl.sendPC.setLocalDescription(offer).then(function(){
					if (consultationVideoPageControl.ifLog) {
						 console.log("set local offer succ");
					}
					
					window.socketObj.socketIO.emit('offer',socketUserName,JSON.stringify(offer));
				}).catch(function(e){
					console.log("===sendPC set local offer error==="+e);
				});
			},
			sendPCAddStreamEvent : function(e){
				if(consultationVideoPageControl.ifLog){
					console.log("===sendPC get remote media stream===");
				}
				consultationVideoPageControl.remoteStream = e.stream;
				consultationVideoPageControl.remotevideoEle.srcObject = e.stream;
			},
			sendPCIcecandidateEvent : function(evt){
				if(consultationVideoPageControl.ifLog){
					console.log("===sendPC candidate==="+JSON.stringify(evt.candidate));
				}
				if (evt.candidate) {
					window.socketObj.socketIO.emit('candidate', socketUserName,JSON.stringify(evt.candidate));
				}
			},
			sendPCSetRemoteDesc : function(sdp){
				consultationVideoPageControl.sendPC.setRemoteDescription(new RTCSessionDescription(sdp)).then(function(){
					consultationVideoPageControl.sendPCSetRemoteDescSucc();
				}).catch(function(e){
					console.log("setRemote Offer Error  :"+e);
				});
			},
			sendPCSetRemoteDescSucc : function(){
				if (consultationVideoPageControl.ifLog) {
					 console.log("set remote offer succ");
				}
				
				consultationVideoPageControl.sendPC.addStream(consultationVideoPageControl.localStream);
				consultationVideoPageControl.sendPC.createAnswer(/*options*/).then(function(answer){
					consultationVideoPageControl.sendPCCreateAnswerSucc(answer);
				}).catch(function(e){
					console.log("create answer Error"+e);
				});
			},
			sendPCCreateAnswerSucc : function(answer){
				consultationVideoPageControl.sendPC.setLocalDescription(answer).then(function(){
					if (consultationVideoPageControl.ifLog) {
						 console.log("set local answer succ");
						 console.log("发送answer");
					}
					
					window.socketObj.socketIO.emit('answer', socketUserName,JSON.stringify(answer));
				}).catch(function(e){
					console.log("set answer Error"+e);
				});
				
			},
			addIceCandidate : function(candidate){
				if (candidate) {
					consultationVideoPageControl.sendPC.addIceCandidate(new RTCIceCandidate(candidate));
				}
			}
	};
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	